import Vue from 'vue'
import App from './App.vue'
import router from './router'
import store from './store'
import axios from 'axios'
import 'amfe-flexible/index.js'
import { Swipe, SwipeItem, Image, Divider, Tabbar, TabbarItem, Sidebar, SidebarItem, Search,
  Checkbox, CheckboxGroup, Card, SubmitBar, Toast, NavBar, Grid, GridItem, Lazyload,
  Row, Col, Tag, Icon, Cell, CellGroup, GoodsAction, GoodsActionIcon, GoodsActionButton,
  Sku, AddressList, AddressEdit, Area, Tab, Tabs, Button, PasswordInput, NumberKeyboard,
  ImagePreview, Stepper, Dialog, ContactCard, ContactList, ContactEdit, Popup, Field, Panel,
  RadioGroup, Radio } from 'vant'

Vue.use(Swipe).use(SwipeItem).use(Image).use(Divider).use(Tabbar).use(TabbarItem).use(Sidebar).use(SidebarItem).use(Search)
  .use(Checkbox).use(CheckboxGroup).use(Card).use(SubmitBar).use(Toast).use(NavBar).use(Grid).use(GridItem).use(Lazyload)
  .use(Row).use(Col).use(Tag).use(Icon).use(Cell).use(CellGroup).use(GoodsAction).use(GoodsActionIcon).use(GoodsActionButton)
  .use(Sku).use(AddressList).use(AddressEdit).use(Area).use(Tab).use(Tabs).use(Button).use(PasswordInput).use(NumberKeyboard)
  .use(ImagePreview).use(Stepper).use(Dialog).use(ContactCard).use(ContactList).use(ContactEdit).use(Popup).use(Field).use(Panel)
  .use(RadioGroup).use(Radio)

Vue.config.productionTip = false
Vue.prototype.axios = axios

router.beforeEach((to, from, next) => {
  // store已存在用户信息直接进入页面
  if (store.state.openId) {
    next()
    return
  }
  let url = window.location.href
  url = url.substring(url.indexOf('code=') + 5)
  const code = url.substring(0, url.indexOf('&'))
  if (code !== undefined && code !== '' && code !== null) {
    const param = { code: code }
    axios.post('/wx/auth', param).then(resp => {
      if (resp.data.code !== -1) {
        store.state.openId = resp.data.openId
        next()
      } else {
        self.$toast('用户授权出错！')
      }
    }).catch(error => {
      console.log(error)
    })
  } else {
    // 这个redirectUrl用 当前页路径或者tof.fullPath(将要进入的路径)
    let redirectUrl = 'https://www.gsfoodmall.com'
    redirectUrl = encodeURIComponent(redirectUrl)
    const appId = 'wx3e9e6709927b3d9b'
    window.location.href = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appId}&redirect_uri=${redirectUrl}&response_type=code&scope=snsapi_userinfo&state=123#wechat_redirect`
  }
})

new Vue({
  router,
  store,
  render: h => h(App)
}).$mount('#app')
